﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer.Core.FSM
{
    public class FsmSystem<T>
    {
        public FsmSystem(T param) 
        {
            this.P= param;
        }
        private Dictionary<string,State<T>> dict= new Dictionary<string,State<T>>();
        public string CurrentStateId { get; private set; }
        public State<T> CurrentState{ get; private set; }

        public T P;
        public void AddState(string stateId,State<T> state)
        {
            if(CurrentState is null)
            {
                CurrentState = state;
                CurrentStateId = stateId;
            }
            dict[stateId] = state;
            state.fsm = this;
        }
        public void RemoveState(string stateId)
        {
            if(dict.ContainsKey(stateId))
            {
                dict[stateId].fsm = null;
                dict.Remove(stateId);
            }
        }
        public void ChangeState(string stateId)
        {
            if (CurrentStateId == stateId)
                return;
            if (!dict.ContainsKey(stateId))
                return;
            if(CurrentState!=null)
            {
                CurrentState.OnExit();
            }
            CurrentStateId=stateId;
            CurrentState = dict[stateId];
            CurrentState.OnEnter();
        }
        public void Update()
        {
            if(CurrentState!=null)
            {
                CurrentState.OnUpdate();
            }
        }
    }
}
